﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using ESRI.ArcGIS.Geodatabase;

namespace Akiha.Core
{
    //设计字段的bindingSource

    



    //字段属性的枚举值
    public enum FieldProperty
    {
        //可编辑
        Name=0,
        AliasName=1,
        Type=2,     
        Length=3,
        Precision=4,
        Scale=5,
        //不需编辑
        Editable = 6,
        IsNullable = 7,
        Required = 8,

        //VarType=9
    }



    class FieldsWrapper : BindingList<IField>, ITypedList
    {

        private IFields m_pFields=null;

        private ITable m_pTable = null;

        private List<PropertyDescriptor> fakePropertiesList = new List<PropertyDescriptor>();

        //记录新添加的字段
        //private List<IField> m_lstField = new List<IField>();



        public FieldsWrapper(ITable pTable)
        {
            m_pTable = pTable;

            m_pFields = pTable.Fields;
            GenerateFakeProperties();
            AddData();
            AllowNew = true;
            AllowRemove = true;
        }

        

        //添加字段时响应
        protected override void OnAddingNew(AddingNewEventArgs e)
        {
            // Check that we can still add rows, this property could have been changed
            if (AllowNew)
            {
                // Need to create a new IRow
                IField pField = new FieldClass();
                m_pTable.AddField(pField);
                e.NewObject = pField;
                //m_lstField.Add(pField);       
                base.OnAddingNew(e);
            }
        }

        //移除字段
        protected override void RemoveItem(int index)
        {
            
            if (AllowRemove)
            {
                try
                {
                    IField pField = Items[index] as Field;
                    if (!CheckFields(pField))
                    {
                        return;
                    }
                    m_pTable.DeleteField(pField);
                    base.RemoveItem(index);
                }
                catch (Exception ex)
                {
                    //不用过滤直接弹出错误给上一级
                    throw ex;
                }
            }
        }
        //检查该字段是否可以编辑或者删除
        //返回true表示可以编辑或删除
        private bool CheckFields(IField pField)
        {
            if (pField == null)
            {
                return false;
            }
            esriFieldType esriType = pField.Type;
            if ((int)esriType <= 5)
            {
                return true;
            }
            return false;
        }
        



        #region ITypedList 成员

        public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
        {
            PropertyDescriptorCollection propCollection = null;
            if (null == listAccessors)
            {
                // Return all properties
                propCollection = new PropertyDescriptorCollection(fakePropertiesList.ToArray());
            }
            else
            {
                // Return the requested properties by checking each item in listAccessors
                // to make sure it exists in our property collection.
                List<PropertyDescriptor> tempList = new List<PropertyDescriptor>();
                foreach (PropertyDescriptor curPropDesc in listAccessors)
                {
                    if (fakePropertiesList.Contains(curPropDesc))
                    {
                        tempList.Add(curPropDesc);
                    }
                }
                propCollection = new PropertyDescriptorCollection(tempList.ToArray());
            }

            return propCollection;
        }

        public string GetListName(PropertyDescriptor[] listAccessors)
        {
            return null;
        }

        #endregion


        private void GenerateFakeProperties()
        {
            //获取第一个字段
            IField pField = m_pFields.get_Field(0);
            for (int fieldCount = 0; fieldCount <9 ; fieldCount++)
            {                             
                FieldsTypeDescripter newPropertyDesc = new FieldsTypeDescripter(pField, fieldCount);
                fakePropertiesList.Add(newPropertyDesc);
            }

        }

        //初始时添加IField字段到当前集合
        public void AddData()
        {
            for (int i = 0; i < m_pFields.FieldCount; i++)
            {
                IField pField=m_pFields.get_Field(i);
                Add(pField);
            }
        }




    }






    class FieldsTypeDescripter : PropertyDescriptor
    {

        //字段属性的索引，
        private FieldProperty wrappedFieldIndex;     
        private bool isEditable=false;
        private Type m_FieldPorpertyType = null;



        //构造函数
        public FieldsTypeDescripter(IField pField, int fieldPropertyIndex)
            :base(((FieldProperty)fieldPropertyIndex).ToString(),null)
        {
            wrappedFieldIndex =(FieldProperty)fieldPropertyIndex;
            //判断是否可以编辑
            //新建的字段，名称，别名，类型，精度，范围这些才是可编辑选项

            if (fieldPropertyIndex <= 5)
            {
                isEditable = true;
            }

            string strPorperty = wrappedFieldIndex.ToString();
            Type type = typeof(IField);
            var memberInfo = type.GetProperty(strPorperty);
            object value = memberInfo.GetValue(pField, null);
            m_FieldPorpertyType = value.GetType();
            
           

            
        }



        public override bool CanResetValue(object component)
        {
            return false;
        }

        public override Type ComponentType
        {
            get
            {
                return typeof(IField);
            }
        }

        public override object GetValue(object component)
        {
            string strPorperty= wrappedFieldIndex.ToString();
            IField pFeild=component as IField;        
            var  propertyInfo=typeof(IField).GetProperty(strPorperty);
            object value=propertyInfo.GetValue(pFeild,null);
            return value;
        }


        
        public override bool IsReadOnly
        {
            get
            {
                return false;
            }
        }


        public override Type PropertyType
        {
            get
            {
                return m_FieldPorpertyType;
            }
        }

        public override TypeConverter Converter
        {
            get
            {
                return base.Converter;
            }
        }

        public override void ResetValue(object component)
        {
           
        }

        public override void SetValue(object component, object value)
        {
            //对字段进行过滤,关键字段是不能修改的
            if (!CheckFields(component as IField))
            {
                return;
            }
            try
            {
                string strPorperty = wrappedFieldIndex.ToString() + "_2";
                IField pField = component as IField;

               
                
            
                IFieldEdit pFieldEdit = pField as IFieldEdit;
                var propertyInfo = typeof(IFieldEdit).GetProperty(strPorperty);
                propertyInfo.SetValue(pFieldEdit, value, null);
            }
            catch (Exception ex)
            {
                //修改字段参数后出错抛出错误到上一级
                throw ex;
            }
        }

        //检查字段是否可以更改
        //这里不是通过字段名称，确定而是通过字段类型确定。
        /// <summary>
        /// 可以修改的字段返回true
        /// </summary>
        /// <param name="pField"></param>
        /// <returns></returns>
        private bool CheckFields(IField pField)
        {
            if (pField==null)
            {
                return false;
            }
            esriFieldType esriType = pField.Type;
            if ((int)esriType<=5)
            {
                return true;
            }
            return false;
        }



        public override bool ShouldSerializeValue(object component)
        {
            return false;
        }
    }
}
